package com.frikinet.lifeguard.tests;

import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.PropertyConfigurator;
import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.AbstractHandler;
import org.eclipse.jetty.server.handler.DefaultHandler;
import org.eclipse.jetty.server.handler.HandlerList;
import org.eclipse.jetty.server.nio.SelectChannelConnector;

import com.frikinet.lifeguard.Lifeguard;
import com.frikinet.lifeguard.model.PostImage;
import com.frikinet.lifeguard.util.HibernateUtil;


public class JettyTest extends AbstractHandler
{
	@Override
	public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
	{
		String pattern = "^/(.*?)\\.jpg$";
		if(Pattern.matches(pattern, target))
		{
			Matcher matcher = Pattern.compile(pattern).matcher(target);
			matcher.find();
			String uid = matcher.group(1);
			PostImage image = HibernateUtil.get(PostImage.class, "uid", uid);
			if(image != null)
			{
				response.setContentType("image/jpeg");
				response.setStatus(HttpServletResponse.SC_OK);
				baseRequest.setHandled(true);
				response.getOutputStream().write(image.getImage());
			}
		}
	}

	public static void main(String args[]) throws Exception
	{
		PropertyConfigurator.configure(Lifeguard.class.getClassLoader().getResource("log4.properties"));
		Server server = new Server();
		SelectChannelConnector connector = new SelectChannelConnector();
		connector.setHost("127.0.0.1");
		connector.setPort(8181);
		server.setConnectors(new Connector[] {
				connector
		});
		
		HandlerList list = new HandlerList();
		list.addHandler(new JettyTest());
		list.addHandler(new DefaultHandler());
		server.setHandler(list);
		server.start();
		server.join();
	}
}
